#include "stdafx.h"
#include "Filesystem.h"

#include "Exception.h"

namespace Cvekas {

const std::string redirect_file = "resources.redirect";
std::string redirection_prefix = "";

void Filesystem::init()
{
	if(fileExists(redirect_file))
	{
		std::ifstream in(redirect_file.c_str());
		in >> redirection_prefix;
	}
}

void Filesystem::init(const std::string& subdir)
{
	init();
	redirection_prefix += subdir;
}

bool Filesystem::fileExists(const std::string& path)
{
	return (_access(path.c_str(), 0) != -1);
}

std::string Filesystem::redirect(const std::string& path)
{
	return redirection_prefix + path;
}

std::string Filesystem::readFileToString(const std::string& path)
{
	if(!fileExists(path))
		throw EXCEPTION("File " + path + " doesn't exist");

	std::string result, line;
	std::ifstream in(path.c_str());
	
	while(std::getline(in, line))
		result += line + '\n';

	return result;
}

void Filesystem::writeStringToFile(const std::string& path, const std::string& str)
{
	std::ofstream out(path.c_str());
	out << str;
}

} // namespace